const Service = require('egg').Service
class UserService extends Service{
    async submit() {
        const {ctx,app} = this;
        const {answerList} = ctx.request.body; // [{id:1,answer:1},{id:2,answer:4}]
        const allP = answerList.map(item=> {
            return new Promise(async (resolve,reject)=>{
                const res = await app.mysql.get('titles', {id:item.id,answer: item.answer});
                if(res) {
                    resolve(res) // 答对了
                } else {
                    resolve(item.id*1) // 打错了返回id
                }
            })
        })
        const list = await Promise.all(allP)
        return {
            // 总分 过滤所有不是id的值
            allScore:  list.filter(item=>typeof item !=='number').reduce((prev,next)=>{
                return prev+=next.score
            },0),
            // 错误题目的id 过滤所有是id的值
            errorTitles: list.filter(item=>typeof item ==='number')
        }

    }
    async getList() {
        const {ctx,app} = this;
        // 先找所有的题目
        const titles = await app.mysql.select('titles')
        // 获取题目对应的选项
        const allP = titles.map(item => {
            return app.mysql.select('options',{
                where: {title_id: item.id}
            })
        })
        const options = await Promise.all(allP) //[[{},{}],[{},{}]]
        // 合并到一起并返回
        return titles.map((item,index) => {
            return {...item,checks: options[index]}
        })
    }
}
module.exports = UserService